﻿<?php
if(!defined('IN_PHPSCUP'))exit('hacking'); 
class DatabaseApp extends BaseApp
{
    function optimize()
    {
	   if(!isset($_GET['task']))
	   {
	   $_GET['task'] ='';
	   }
        $task = $_GET['task']; 
		$tables =array();
        $db = &get_db();
		
		$q = $db->list_tables(DB_NAME);

		if($q){
			while ($rs = $db->fetch_row($q)){
				$pos = strpos($rs[0], '_', 0) + 1;
				if(substr($rs[0],0,$pos) == DB_PREFIX){
					$tables[][] = $rs[0];
				}
			}
		}
		$db->free_result($q);
		unset($rs);
		
		if($task =='optimize')
		{

			for($i=0;$i<count($tables);$i++)
			{
				$db->query("OPTIMIZE TABLE `".$tables[$i][0]."`;");
			}

		   $notice = &get_message(array('msg'=>'Success!','url'=>'','title'=>'Notice'));
		   $notice ->display();
		 
		}

		
        $this->assign('tables', $tables);	    
        $this->assign('view_charset', VIEW_CHARSET);	
        $this->assign('page_title', $GLOBALS['Lang']->_get_lang_var(SITE_TITLE));
        $this->assign('page_description', $GLOBALS['Lang']->_get_lang_var(SITE_DESCRIPTION));
        $this->assign('page_keywords', $GLOBALS['Lang']->_get_lang_var(SITE_KEYWORDS));	
		
        $this->assign('site_url',SITE_URL);
		
        $this->assign('web_view_dir',SITE_URL.'/admin/view/default/');
		
        $this->display('database_opt.view.html');
    }

    function backup()
    {	
	   if(!isset($_GET['task']))
	   {
	   $_GET['task'] ='';
	   }	
        $task = $_GET['task']; 
		
        $db = &get_db();	
		
		if($task =='backup')
		{
			   if(!isset($_POST['tables']))
	          {
	           $_POST['tables'] ='';
	          }
		
			$tables = $_POST['tables'];
			
			$tableid = isset($_GET['tableid'])?$_GET['tableid']:0;
			$fileid = isset($_GET['fileid'])?$_GET['fileid']:0;
			$startfrom = isset($_GET['startfrom'])?$_GET['startfrom']:0;
			$random = isset($_GET['random'])?$_GET['random']:'';
			$sizelimit = isset($_GET['sizelimit'])?$_GET['sizelimit']:0;
			$sizelimit = isset($_POST['sizelimit'])?$_POST['sizelimit']:$sizelimit;
			
			$GLOBALS['sizelimit'] = &$sizelimit;
			
			$GLOBALS['startrow'] = &$startrow;
						
			$fileid = $fileid ? $fileid : 1;
			
			$bak_dir = ROOT_PATH . '/data/database/';
			$default_index = $bak_dir.'index.htm';
			if(!is_dir($bak_dir))
			{
				mkdir($bak_dir,0777);
			}
			if(!file_exists($default_index))
			{
				write_file($default_index,'SCUP');
			}

			if($tables && $fileid==1)
			{
				if(!isset($tables) || !is_array($tables))
				{
		            $notice = &get_message(array('msg'=>'please select backup database','url'=>'','title'=>'Notice'));
		            $notice ->display();
				}
				
			    $random = random(8);
			    $this->cache_write('backup_temp_tables.php', $tables);
			}else
			{
			    if(!$tables = $this->cache_read('backup_temp_tables.php'))
				{
		            $notice = &get_message(array('msg'=>'can not write backup database list','url'=>'','title'=>'Notice'));
		            $notice ->display();
				}
			}
			
			$sql_data = '';
			$tableid = $tableid ? ($tableid - 1) : 0;
			$startfrom = $startfrom ? $startfrom : 0;
			$tablenumber = count($tables);

			for($i = $tableid; $i < $tablenumber && strlen($sql_data) < $sizelimit * 1000; $i++)
			{			

				$sql_data .= $this->sql_dumptable($tables[$i], $startfrom, strlen($sql_data));
				$startfrom = 0;
			}
			
						
			if(trim($sql_data))
			{
				$sqldump = "# Database backup data, auto-generated by PHPSCUP. ".LF;
				$sqldump .= "# -------------------------------------------".LF.LF.$sql_data;

				$tableid = $i;
				$filename = DB_NAME .'_'.date('Ymd').'_'.$random.'_'.$fileid.'.sql';
				$fileid++;
				
				$bakfile = $bak_dir.$filename;
				if(!is_writable($bak_dir))
				{
		            $notice = &get_message(array('msg'=>'sql can not write','url'=>'','title'=>'Notice'));
		            $notice ->display();
				}
				file_put_contents($bakfile, $sqldump);

				$gourl = '?app=database&act=backup&task=backup&sizelimit='.$sizelimit.'&tableid='.$tableid.'&fileid='.$fileid.'&startfrom='.$startrow.'&random='.$random;
			
		        $notice = &get_message(array('msg'=>'backup file:'.$filename.' ... '.'backup write success','url'=>$gourl,'title'=>'Notice'));
		        $notice ->display();				
				
			}else
			{
				$this->cache_delete('backup_temp_tables.php');
				$gourl = '?app=database&act=restore';				
				$notice = &get_message(array('msg'=>'backup database success','url'=>$gourl,'title'=>'Notice'));
		        $notice ->display();	
			}
		}		

		
		
		$size = $bktables = $bkresults = $results = array();
		$k = 0;
		$totalsize = 0;
		$sql = "SHOW TABLES FROM ".DB_NAME;
		$q = $db->query($sql);
			
		while($rs = $db->fetch_row($q))
		{
			
			  $pos = strpos($rs[0], '_', 0) + 1;
				if(substr($rs[0],0,$pos) == DB_PREFIX)
				{
					$tables[$k] = $rs[0];
		            $count = $db->fetch_array($db->query("SELECT count(*) as number FROM $rs[0] WHERE 1"));					
					$results[$k] = $count['number'];
					$bktables[$k] = $rs[0];
					$bkresults[$k] = $count['number'];
					$q2 = $db->query("SHOW TABLE STATUS FROM `".DB_NAME."` LIKE '".$rs[0]."'");
					$s = $db->fetch_array($q2);
					$size[$k] = round($s['Data_length']/1024/1024, 2);
					$totalsize += $size[$k];
					$k++;
				}
		}
		$db->free_result($q);
		unset($rs);

        $this->assign('bktables', $bktables);
	    $this->assign('totalsize', $totalsize);
		$this->assign('bkresults', $bkresults);
		$this->assign('size', $size);		
		$this->assign('color', '');
			    
        $this->assign('view_charset', VIEW_CHARSET);	
        $this->assign('page_title', $GLOBALS['Lang']->_get_lang_var(SITE_TITLE));
        $this->assign('page_description', $GLOBALS['Lang']->_get_lang_var(SITE_DESCRIPTION));
        $this->assign('page_keywords', $GLOBALS['Lang']->_get_lang_var(SITE_KEYWORDS));	
		
        $this->assign('site_url',SITE_URL);
		
        $this->assign('web_view_dir',SITE_URL.'/admin/view/default/');
		
        $this->display('database_bup.view.html');

    }

    function get_extension ($name)
	{
	return strtolower(trim(strrchr($name, '.'), '.'));
    }

    function restore()
    {	
		   if(!isset($_GET['task']))
	   {
	   $_GET['task'] ='';
	   }
	     $task = $_GET['task']; 
			if($task =='restore')
			{

                $pre = isset($_GET['pre'])?$_GET['pre']:'';				
				$fileid = isset($_GET['fileid'])?$_GET['fileid']:0;
				$filename = isset($_GET['filename'])?$_GET['filename']:'';				
				if($filename && $this->get_extension($filename)=='sql')
				{
				
					$sql_file = ROOT_PATH . '/data/database/'.$filename;
					if(!file_exists($sql_file))
					{
		                $notice = &get_message(array('msg'=>$sql_file.' ...... file not exists','url'=>'?app=database&act=restore','title'=>'Notice'));
	                    $notice ->display();						
						
					}
					$sql = file_get_contents($sql_file);
					$this->sql_execute($sql);
					
		            $notice = &get_message(array('msg'=>'restore database success','url'=>'?app=database&act=backup','title'=>'Notice'));
	                $notice ->display();
					
				}else
				{
				
					$fileid = $fileid ? $fileid : 1;
					$filename = $pre.$fileid.'.sql';
					$sql_file =  ROOT_PATH . '/data/database/'.$filename;

					if(file_exists($sql_file))
					{
						$sql = file_get_contents($sql_file);
						$this->sql_execute($sql);
						$fileid++;
						
						$gourl = "?app=database&act=restore&task=restore&pre=$pre&fileid=$fileid";
		                $notice = &get_message(array('msg'=>'backup_file:'.$filename.' ...... restore sucess','url'=>$gourl,'title'=>'Notice'));
	                    $notice ->display();
						
					}else
					{
	
		                $notice = &get_message(array('msg'=>'restore database success','url'=>'?app=database&act=restore','title'=>'Notice'));
	                    $notice ->display();
					}
				}
			}

			     $sqlfiles = glob(ROOT_PATH . '/data/database/*.sql');
	
				 if(is_array($sqlfiles))
				 {
					 $prepre = '';
					 $info = $infos = array();
					 foreach($sqlfiles as $k => $sqlfile)
					 {
						 preg_match("/([a-z0-9_]+_[0-9]{8}_[0-9a-z]{8}_)([0-9]+)\.sql/i",basename($sqlfile),$num);
						 $info['filename'] = basename($sqlfile);
						 $info['filesize'] = round(filesize($sqlfile)/(1024*1024), 2);
						 $info['maketime'] = date('Y-m-d H:i:s', filemtime($sqlfile));
						 $info['pre'] = $num[1];
						 $info['number'] = $num[2];
						 if(!$k) $prebgcolor = '#CCCCCC';
						 if($info['pre'] == $prepre)
						 {
							 $info['bgcolor'] = $prebgcolor;
						 }else
						 {
							 $info['bgcolor'] = $prebgcolor == '#CCCCCC' ? '#E4EDF9' : '#CCCCCC';
						 }
						 $prebgcolor = $info['bgcolor'];
						 $prepre = $info['pre'];
						 $info['a_delete'] = "?app=database&act=delete&pre=".$info['pre'];
						 $info['a_restore'] = "?app=database&act=restore&task=restore&pre=".$info['pre'];
						 $infos[] = $info;
					 }
				 }	

        $this->assign('infos', $infos);
	
        $this->assign('view_charset', VIEW_CHARSET);	
        $this->assign('page_title', $GLOBALS['Lang']->_get_lang_var(SITE_TITLE));
        $this->assign('page_description', $GLOBALS['Lang']->_get_lang_var(SITE_DESCRIPTION));
        $this->assign('page_keywords', $GLOBALS['Lang']->_get_lang_var(SITE_KEYWORDS));	
		
        $this->assign('site_url',SITE_URL);
		
        $this->assign('web_view_dir',SITE_URL.'/admin/view/default/');
		
        $this->display('database_res.view.html');



    }


    function delete()
    {

        $pre = isset($_GET['pre'])?$_GET['pre']:'';
		
		$sqlfiles = glob(ROOT_PATH . '/data/database/*.sql');
		if(is_array($sqlfiles))
		{
				foreach($sqlfiles as $k => $sqlfile)
				{
					if(preg_match("/($pre)([0-9]+)\.sql/i",basename($sqlfile)))
					{
						$sysmsg = 'delete &nbsp;&nbsp;'.$sqlfile.' ...... success';
						@unlink($sqlfile);
					}
				}
		}
		
		$gourl = '?app=database&act=restore';				
		$notice = &get_message(array('msg'=>$sysmsg,'url'=>$gourl,'title'=>'Notice'));
	    $notice ->display();

    }


    function sql()
    {
	   if(!isset($_GET['task']))
	   {
	   $_GET['task'] ='';
	   }	
        $task = $_GET['task']; 
	
        $db = &get_db();
		$tables='';
		
		if($task =='sql')
		{
                $t = intval($_POST['t']);	
                 $sql = $_POST['sql'];
                $upsql = $_POST['upsql'];

	          if($t==2)
		      {
		       $sqlfile= ROOT_PATH . '/' . UPFILE_PATH . "/$upsql";


		       $sql_ex = file_get_contents($sqlfile);
		       $this->sql_execute($sql_ex);

		       @unlink($sqlfile);
	           }
		       elseif($t==1)
		       {
                $timestamp = time();
/*		        $sql=StripSlashes($sql);
		          if($pre!='scup_')
		          {
			       $sql=str_replace("scup_",DB_PREFIX,$sql);
		          }		*/

				get_dir(ROOT_PATH . '/' . UPFILE_PATH ."/database");

		         write_file(ROOT_PATH . '/' . UPFILE_PATH ."/database/$timestamp.sql",$sql);
		         $sql_ex = file_get_contents(ROOT_PATH . '/' . UPFILE_PATH ."/database/$timestamp.sql");
		        $this->sql_execute($sql_ex);

		        unlink(ROOT_PATH . '/' . UPFILE_PATH ."/database/$timestamp.sql");

	            }

		   $notice = &get_message(array('msg'=>'Scucces!','url'=>'?app=database&act=sql','title'=>'Notice'));
		   $notice ->display();
		 
		}

		
        $this->assign('tables', $tables);	    
        $this->assign('view_charset', VIEW_CHARSET);	
        $this->assign('page_title', $GLOBALS['Lang']->_get_lang_var(SITE_TITLE));
        $this->assign('page_description', $GLOBALS['Lang']->_get_lang_var(SITE_DESCRIPTION));
        $this->assign('page_keywords', $GLOBALS['Lang']->_get_lang_var(SITE_KEYWORDS));	
		
        $this->assign('site_url',SITE_URL);
		
        $this->assign('web_view_dir',SITE_URL.'/admin/view/default/');
		
        $this->display('database_sql.view.html');
    }


    function upfile()
    {

if(!isset($_POST["action"]))
{
   $_POST["action"]='';
}		
	
if(!isset($_GET["edit"]))
{
   $_GET["edit"]='';
}	
if(!isset($_GET["picurl"]))
{
  $_GET["picurl"] ='';
}	
		$action = $_POST["action"];

		$edit = $_GET["edit"];
		$picurl = $_GET["picurl"];
		if($edit)
		{
        $this->assign('edit', $edit);		
		}
        if($picurl)
		{
        $this->assign('picurl', $picurl);
		}
						

		if($action == 'post')
		{
		
if(!isset($_POST["edit"]))
{
   $_POST["edit"]='';
}		
if(!isset($_POST["picurl"]))
{
   $_POST["picurl"]='';
}		
				
			   $edit = $_POST["edit"];
		       $picurl = $_POST["picurl"];

		       include(ROOT_PATH.'/lib/upfile.lib.php');	  
	           $upfile = new Upfile('database'); 	  
	           $updata = $upfile->_batch_upfile('');		 
		 		 
		       $newfile = $updata[1]['path'];
		       
			    if($edit=='edit' && $picurl)
		       {
		              $pic_dir= ROOT_PATH . '/' . UPFILE_PATH . '/' . $picurl;
		              del_file($pic_dir);			 
		       }
		 	   

	    echo "<br/><A HREF='?app=database&act=upfile&edit=edit&picurl=$newfile'>修改上传文件</A>";
	     
		$jsfun="upfile";
	    echo "<script>
				if(self==top){
					window.opener.$jsfun('$newfile','upsql');
					window.self.close();
				}else{
					window.parent.$jsfun('$newfile','upsql');
				}
		     </script>";
				
	    exit;
		
		
		}

        $this->assign('id', '');
	    $this->assign('app', 'database');		    
        $this->assign('view_charset', VIEW_CHARSET);	
        $this->assign('page_title', SITE_TITLE);
        $this->assign('page_description', SITE_DESCRIPTION);
        $this->assign('page_keywords', SITE_KEYWORDS);	

        $this->assign('edit', $edit);
        $this->assign('picurl', $picurl);
				
        $this->assign('site_url',SITE_URL);
		
        $this->assign('web_view_dir',SITE_URL.'/admin/view/default/');		
		
        $this->display('upfile.view.html');
    }







    function cache_write($file, $string, $type = 'array')
	{
	     if(is_array($string))
		 {
		         $type = strtolower($type);
		         if($type == 'array')
				 {
			            $string = "<?php\n return ".var_export($string,TRUE).";\n?>";
		         }elseif($type == 'constant')
				 {
			            $data='';
			            foreach($string as $key => $value) $data .= "define('".strtoupper($key)."','".addslashes($value)."');\n";
			            $string = "<?php\n".$data."\n?>";
		         }
	     }
	file_put_contents(ROOT_PATH . '/data/database/'.$file, $string);
   }

   function cache_read($file, $mode = 'i')
   {
	     $cachefile = ROOT_PATH . '/data/database/' . $file;
	    if(!file_exists($cachefile)) return array();
	    return $mode == 'i' ? include $cachefile : file_get_contents($cachefile);
   }

   function cache_delete($file)
   {
	    return @unlink(ROOT_PATH . '/data/database/'.$file);
   }

   function sql_dumptable($table, $startfrom = 0, $currsize = 0)
   {
	
		$sizelimit = & $GLOBALS['sizelimit'];
			
		$startrow  = & $GLOBALS['startrow'];

	   $db = &get_db();

	   if(!isset($tabledump)) $tabledump = '';
	   $offset = 100;
	   if(!$startfrom)
	   {
		$tabledump = "DROP TABLE IF EXISTS $table;\n";
		$createtable = $db->query("SHOW CREATE TABLE $table");
		$create = $db->fetch_row($createtable);
		$tabledump .= $create[1].";\n\n";
	   }

	   $tabledumped = 0;
	   $numrows = $offset;
	   while($currsize + strlen($tabledump) < $sizelimit * 1000 && $numrows == $offset)
	   {
		        $tabledumped = 1;
		        $rows = $db->query("SELECT * FROM $table LIMIT $startfrom, $offset");
		        $numfields = $db->num_fields($rows);
		        $numrows = $db->num_rows($rows);
		        while ($row = $db->fetch_row($rows))
				{
			           $comma = "";
			           $tabledump .= "INSERT INTO $table VALUES(";
			           for($i = 0; $i < $numfields; $i++)
					   {
				              $tabledump .= $comma."'".mysql_escape_string($row[$i])."'";
				              $comma = ",";
			           }
			           $tabledump .= ");\n";
		        }
		        $startfrom += $offset;
	   }
	    $startrow = $startfrom;
	    $tabledump .= "\n";
	    return $tabledump;
    }



function sql_execute($sql){
	$db = &get_db();
	
    $sqls = $this->sql_split($sql);
	if(is_array($sqls)){
		foreach($sqls as $sql){
			if(trim($sql) != ''){
				$db->query($sql);
			}
		}
	}else{
		$db->query($sqls);
	}
	return true;
}

function sql_split($sql){
	$db = &get_db();
	if($db->version() > '4.1'){
		$sql = preg_replace("/TYPE=(InnoDB|MyISAM)( DEFAULT CHARSET=[^; ]+)?/", "TYPE=\\1 DEFAULT CHARSET=utf8",$sql);
	}
	$sql = str_replace("\r", "\n", $sql);
	$ret = array();
	$num = 0;
	$queriesarray = explode(";\n", trim($sql));
	unset($sql);
	
	foreach($queriesarray as $query){
		$ret[$num] = '';
		$queries = explode("\n", trim($query));
		$queries = array_filter($queries);
		
		foreach($queries as $query){
			$str1 = substr($query, 0, 1);
			if($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
		}
		$num++;
	}
	return($ret);
}


  
}
?>